package io.github.xbeeant.eoffice.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.github.xbeeant.core.ApiResponse;
import io.github.xbeeant.core.ErrorCodeConstant;
import io.github.xbeeant.core.IdWorker;
import io.github.xbeeant.core.JsonHelper;
import io.github.xbeeant.eoffice.config.AbstractSecurityMybatisPageHelperServiceImpl;
import io.github.xbeeant.eoffice.mapper.ResourcesMapper;
import io.github.xbeeant.eoffice.mapper.ResourcesVersionMapper;
import io.github.xbeeant.eoffice.model.*;
import io.github.xbeeant.eoffice.po.ResourceInfo;
import io.github.xbeeant.eoffice.service.*;
import io.github.xbeeant.spring.mybatis.antdesign.PageResponse;
import io.github.xbeeant.spring.mybatis.pagehelper.IMybatisPageHelperDao;
import io.github.xbeeant.spring.mybatis.pagehelper.PageBounds;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.github.xbeeant.eoffice.model.Resources;
import io.github.xbeeant.eoffice.service.IResourcesService;

/**
 * 用户资源
 */
@Service
public class ResourcesServiceImpl extends AbstractSecurityMybatisPageHelperServiceImpl<Resources, Long> implements IResourcesService {

    @Autowired
    private IAttachmentService attachmentService;

    @Autowired
    private ResourcesMapper resourcesMapper;

    @Autowired
    private ResourcesVersionMapper resourcesVersionMapper;

    @Autowired
    private IFolderService folderService;

    @Autowired
    private IResourcesPermService resourcesPermService;

    @Autowired
    private IFolderUserService folderUserService;

    @Override
    public IMybatisPageHelperDao<Resources, Long> getRepositoryDao() {
        return this.resourcesMapper;
    }

    @Override
    public void setDefaults(Resources record) {
        if (record.getRid() == null) {
            record.setRid(IdWorker.getId());
        }
    }

    @Override
    public ApiResponse<PageResponse<Resources>> fuzzySearchByPagerIncludeSharedFolder(Resources example, PageBounds pageBounds) {
        ApiResponse<PageResponse<Resources>> apiResponse = new ApiResponse<>();
        PageHelper.orderBy(pageBounds.getOrders());
        PageHelper.startPage(pageBounds.getPage(), pageBounds.getLimit());
        Page<Resources> result = resourcesMapper.fuzzySearchIncludeSharedFolder(example);
        if (result.isEmpty()) {
            apiResponse.setResult(ErrorCodeConstant.NO_MATCH, ErrorCodeConstant.NO_MATCH_MSG);
            return apiResponse;
        }
        PageResponse<Resources> pageList = new PageResponse<>(result, result.getTotal(), pageBounds.getPage());
        apiResponse.setData(pageList);
        return apiResponse;
    }

    @Override
    public boolean isOwner(Long rid, String userId) {
        Resources example = new Resources();
        example.setRid(rid);
        example.setCreateBy(userId);
        Page<Resources> resources = resourcesMapper.selectByExample(example, new PageBounds(0, 1));
        return !CollectionUtils.isEmpty(resources);
    }

    @Override
    public ApiResponse<ResourceInfo> latestVersion(Long rid) {
        ApiResponse<ResourceInfo> result = new ApiResponse<>();
        Resources resources = resourcesMapper.selectByPrimaryKey(rid);
        ResourceInfo resourceInfo = JsonHelper.toObject(JsonHelper.toJsonString(resources), ResourceInfo.class);
        ResourcesVersion resourcesVersion = resourcesVersionMapper.latest(rid);
        ApiResponse<Attachment> attachmentApiResponse = attachmentService.selectByPrimaryKey(resourcesVersion.getAid());
        resourceInfo.setLatest(attachmentApiResponse.getData());
        result.setData(resourceInfo);
        return result;
    }

    @Override
    public ApiResponse<ResourceInfo> versionInfo(Long rid, Long vid) {
        ApiResponse<ResourceInfo> result = new ApiResponse<>();
        Resources resources = resourcesMapper.selectByPrimaryKey(rid);
        ResourceInfo resourceInfo = JsonHelper.toObject(JsonHelper.toJsonString(resources), ResourceInfo.class);
        ResourcesVersion resourcesVersion = resourcesVersionMapper.selectByPrimaryKey(vid);
        ApiResponse<Attachment> attachmentApiResponse = attachmentService.selectByPrimaryKey(resourcesVersion.getAid());
        resourceInfo.setLatest(attachmentApiResponse.getData());
        result.setData(resourceInfo);
        return result;
    }

    @Override
    public boolean hasPermission(Resources resources, Long fid, Long userId) {
        // 权限校验
        boolean hasPermission = false;
        if (resources.getCreateBy().equalsIgnoreCase(String.valueOf(userId))) {
            return true;
        }
        ResourcesPerm resourcesPerm = new ResourcesPerm();
        resourcesPerm.setRid(resources.getRid());
        resourcesPerm.setTargetId(userId);
        ApiResponse<ResourcesPerm> resourcesPermApiResponse = resourcesPermService.selectOneByExample(resourcesPerm);
        if (resourcesPermApiResponse.getSuccess()) {
            hasPermission = resourcesPermApiResponse.getData().hasPermission();
        }
        // 没有资源权限，校验是否有文件夹权限
        if (!hasPermission) {
            FolderUser folderUser = new FolderUser();
            folderUser.setUid(userId);
            folderUser.setFid(fid);
            ApiResponse<FolderUser> folderUserApiResponse = folderUserService.selectOneByExample(folderUser);
            if (folderUserApiResponse.getSuccess()) {
                hasPermission = folderUserApiResponse.getData().hasPermission();
            }
        }
        return hasPermission;
    }

    @Override
    public ApiResponse<Resources> insertSelective(Resources record) {
        // 如果没有选择文件夹，默认设置为 home的文件夹
        if (null == record.getFid()) {
            Folder folderExample = new Folder();
            folderExample.setType("home");
            folderExample.setCreateBy(record.getCreateBy());
            ApiResponse<Folder> folderApiResponse = folderService.selectOneByExample(folderExample);
            if (!folderApiResponse.getSuccess()) {
                // 初始化一个home的文件夹
                folderExample.setFname("我的地盘");
                folderApiResponse = folderService.insertSelective(folderExample);
            }
            record.setFid(folderApiResponse.getData().getFid());
        }
        return super.insertSelective(record);
    }
}
